<template>
  <div>
    <el-dialog title="修改个人资料" width="960px" top="11vh" :visible.sync="showProfile"
               class="user-manage-look-dialog" @close="closeProfile">
      <div class="user-manage-edit-box">
        <div class="avatar-edit-con">
          <span class="title">头像：</span>
          <pan-thumb :image="image?image:require('../../../assets/common_images/avatar.png')"/>
          <el-button type="primary" icon="el-icon-upload" size="mini" class="upload-avatar-btn"
                     @click="imagecropperShow=true">上传头像
          </el-button>
        </div>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-position="right" size="medium" label-width="auto"
                 class="demo-ruleForm">
          <div class="user-info-box">
            <el-form-item label="姓名:" prop="lpNickName">
              <el-input v-model="ruleForm.lpNickName" style="width: 280px" placeholder="请输入姓名"
                        :clearable="true"></el-input>
            </el-form-item>
            <el-form-item label="登录名:" class="position-label">
              <span style="width: 280px">{{ruleForm.lpUserName}}</span>
            </el-form-item>
          </div>

          <div class="user-info-box">
            <el-form-item label="手机号:" prop="lpUserTel">
              <el-input v-model="ruleForm.lpUserTel" style="width: 280px" placeholder="请输入手机号"></el-input>
            </el-form-item>
            <div class="edit-init-login">
              <span class="title">修改登录密码：</span>
              <el-button type="danger" size="mini" class="init-pwd"
                         @click="modifyPwd(ruleForm.id)">修改登录密码
              </el-button>
            </div>
          </div>
          <el-form-item label="邮箱:">
            <el-input v-model="ruleForm.lpMail" style="width: 280px" placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-form-item label="工号:">
            <span style="width: 280px">{{ruleForm.lpWorkNum}}</span>
          </el-form-item>

          <el-form-item label="所属部门:">
            <span style="width: 280px">{{ruleForm.officeName}}</span>
          </el-form-item>
          <el-form-item label="用户角色:">
            <span style="width: 280px">{{ruleForm.className}}</span>
          </el-form-item>
        </el-form>
      </div>

      <div class="user-opt-btn">
        <el-button size="small" type="success" class="opt-box" @click="saveProfile">保存</el-button>
        <el-button size="small" class="opt-box" @click="closeProfile">取消</el-button>
      </div>

      <image-cropper
        v-show="imagecropperShow"
        :key="imagecropperKey"
        :width="300"
        :height="300"
        url="https://www.lanpin123.com"
        lang-type="zh"
        @close="cropClose"
        @crop-upload-success="cropSuccess"
      />
    </el-dialog>

    <el-dialog width="810px" title="修改登录密码" :visible.sync="innerVisible" top="15vh" class="inner-dialog"
               @close="closePwd">
      <el-form :model="pwdForm" :rules="pwdRules" ref="pwdForm" label-width="auto" class="demo-ruleForm">
        <el-form-item label="原密码：" prop="oldPass">
          <el-input type="password" v-model="pwdForm.oldPass" style="width: 450px" placeholder="请输入原登录密码"
                    :clearable="true"></el-input>
        </el-form-item>
        <el-form-item label="新密码：" prop="newPass">
          <el-input type="password" v-model="pwdForm.newPass" style="width: 450px" placeholder="请输入新密码"
                    :clearable="true"></el-input>
        </el-form-item>
        <el-form-item label="确认密码：" prop="checkPass">
          <el-input type="password" v-model="pwdForm.checkPass" style="width: 450px" placeholder="请再次输入新密码"
                    :clearable="true"></el-input>
        </el-form-item>

        <span class="tip-text">注：如若忘记原密码，请联系后台管理员</span>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="danger" style="width:72px" @click="savePwd">修改</el-button>
        <el-button size="small" style="width:72px" @click="closePwd">取消</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
  import ImageCropper from '@/components/ImageCropper';
  import PanThumb from '@/components/PanThumb';
  import {uploadQiniu} from "@/api/qiniu";
  import md5 from 'js-md5';
  import {getInitProfile, getQiNiuUpToken, modifyLoginPwd, modifyProfile} from "../../../api/user/user";

  export default {
    name: "index",
    components: {
      ImageCropper,
      PanThumb
    },
    props: {
      showMaterial: {
        type: Boolean,
        default: false
      }
    },
    data() {
      var checkOldPass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入原登录密码'));
        } else {
          callback();
        }
      };
      var checkNewPass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入新密码'));
        } else {
          callback();
        }
      };
      var checkPass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入新密码'));
        } else if (value !== this.pwdForm.newPass) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        showProfile: false,
        image: '',
        imagecropperShow: false,
        imagecropperKey: 0,
        ruleForm: {
          lpNickName: '',
          lpUserName: '',
          lpUserTel: '',
          lpMail: '',
          lpWorkNum: '',
          lpOfficeId: '',
          classId: '',
          className: '',
          id: '',
          lpUserUrl: ''
        },
        rules: {
          lpNickName: [
            {required: true, message: '请输入姓名', trigger: 'blur'},
            {max: 5, message: '长度最多5个字符', trigger: 'blur'}
          ],
          lpUserTel: [
            {required: true, message: '请输入手机号', trigger: 'blur'},
            {max: 11, message: '长度最多11个字符', trigger: 'blur'}
          ]
        },
        qinNiuToken: '',
        pwdForm: {
          oldPass: '',
          newPass: '',
          checkPass: ''
        },
        pwdRules: {
          oldPass: [
            {required: true, validator: checkOldPass, trigger: 'blur'}
          ],
          newPass: [
            {required: true, validator: checkNewPass, trigger: 'blur'}
          ],
          checkPass: [
            {required: true, validator: checkPass, trigger: 'blur'}
          ]
        },
        innerVisible: false
      }
    },
    created() {
      this.showProfile = this.showMaterial;
    },
    methods: {
      getProfile() {
        getInitProfile().then((res) => {
          let retObj = res;
          if (retObj.code == 0 && retObj.data != null) {
            this.ruleForm = retObj.data;
            this.image = this.ruleForm.lpUserUrl;
          }
        })
      },
      cropSuccess(resData) {
        this.imagecropperShow = false;
        this.imagecropperKey = this.imagecropperKey + 1;
        this.image = resData;
      },
      cropClose() {
        this.imagecropperShow = false;
      },
      modifyPwd() {//修改密码
        this.innerVisible = true;
      },
      closeProfile() {
        this.image = '';
        this.$refs.ruleForm.resetFields();
        this.$store.dispatch('user/changeProfile', false);
      },
      saveProfile() {//保存资料
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            if (this.image && this.image.startsWith('data:image/png;base64,')) {
              uploadQiniu(this.image, this.qinNiuToken, (res) => {//上传图片
                this.ruleForm.lpUserUrl = res;
                this.commonSave();
              });
            } else {
              this.ruleForm.lpUserUrl = this.image;
              this.commonSave();
            }
          } else {
            return false;
          }
        });
      },
      commonSave() {
        modifyProfile(this.ruleForm).then((res) => {
          let retObj = res;
          if (retObj.code == 0) {
            if (retObj.data == 1) {
              this.closeProfile();
              this.$store.dispatch('user/changeAvatar',this.ruleForm.lpUserUrl);
              this.$message.success({message: '修改资料成功', duration: 1000});
            } else {
              this.$message.error({message: '修改资料失败，请重试', duration: 1000});
            }
          }
        })
      },
      closePwd() {
        this.$refs.pwdForm.resetFields();
        this.innerVisible = false;
      },
      savePwd() {
        this.$refs.pwdForm.validate((valid) => {
          if (valid) {
            let sendObj = {};
            sendObj.userPassword = md5(this.pwdForm.oldPass);
            sendObj.newPassword = md5(this.pwdForm.checkPass);

            modifyLoginPwd(sendObj).then((res) => {
              let retObj = res;
              if (retObj.code == 0) {
                if (retObj.data == 1) {
                  this.closePwd();
                  this.$message.success({message: '修改密码成功', duration: 1000});
                } else {
                  this.$message.error({message: '修改密码失败，请重试', duration: 1000});
                }
              }
            })
          } else {
            return false;
          }
        });
      }
    },
    watch: {
      showMaterial(newVal) {
        this.showProfile = newVal;
        if (this.showProfile) {
          getQiNiuUpToken().then((res)=>{
            this.qinNiuToken = res.data;
          });
          this.getProfile();
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .user-manage-look-dialog > > > .el-dialog .el-dialog__header {
    display: flex;
    align-items: center;
    height: 48px;
    background: #F7F8FA;
    padding: 0px 0px 0px 12px;
    .el-dialog__headerbtn {
      top: 15px;
    }
  }

  .user-manage-look-dialog .user-manage-edit-box {
    font-size: 14px;
    color: #606266;
    .avatar-edit-con {
      display: flex;
      align-items: flex-start;
      position: relative;
      margin-left: 25px;
      margin-bottom: 25px;
      .upload-avatar-btn {
        margin-left: 32px;
        margin-top: 60px;
      }
    }
    .user-info-box {
      display: flex;
      .position-label {
        margin-left: 128px;
      }
      .edit-init-login {
        margin-left: 100px;
      }
    }
    .title {
      font-weight: bold;
    }
  }

  .user-opt-btn {
    margin-top: 40px;
    text-align: right;
    .opt-box {
      width: 96px;
    }
  }

  .user-manage-look-dialog .demo-ruleForm {
    > > > .el-input--medium .el-input__inner {
      background: #F7F8FA;
    }
  }

  .inner-dialog > > > .el-dialog .el-dialog__header {
    display: flex;
    align-items: center;
    height: 48px;
    background: #F7F8FA;
    padding: 0px 0px 0px 12px;
    position: fixed;
    width: 810px;
    z-index: 999;
    .el-dialog__headerbtn {
      top: 15px;
    }
  }

  .inner-dialog > > > .el-dialog .el-dialog__body {
    margin-top: 50px;
  }

  .inner-dialog > > > .el-dialog {
    overflow-y: auto;
    height: 400px;
  }

  .inner-dialog > > > .el-form-item__content .el-input__inner {
    background: #F7F8FA;
  }

  .tip-text {
    font-size: 13px;
    color: rgba(60, 175, 255, 1);
  }
</style>
